<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="" prop="subjectType">
        <el-radio-group @change="handleQuery" size="small" v-model="queryParams.subjectType" >
          <el-radio-button label="所有" value="" />
          <el-radio-button label="资产" value="ZC" />
          <el-radio-button label="负债" value="FZ" />
          <el-radio-button label="权益" value="QY" />
          <el-radio-button label="成本" value="CB" />
          <el-radio-button label="损益" value="SY" />
        </el-radio-group>
      </el-form-item>
      <el-form-item label="" prop="hasGtZero">
        <el-radio-group @change="handleQuery" size="small" v-model="queryParams.hasGtZero" >
          <el-radio-button label="所有科目" value="" />
          <el-radio-button label="隐藏为零科目" value="true" />
        </el-radio-group>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain size="small"
            icon="create"
            @click="handleImportDefaultFinSubjectMonth"
            v-hasPermi="['project:FinSubjectMonth:export']"
        >初始化默认数据</el-button>
        <el-button
          type="warning"
          plain size="small"
          icon="Download"
          @click="handleExport"
          v-hasPermi="['project:FinSubjectMonth:export']"
        >导出</el-button>

      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading"  show-summary :summary-method="getSummaries" :data="FinSubjectMonthList" border row-key="subjectId" stripe >
      <el-table-column label="科目编号" align="left" prop="subjectCode" width="180"/>
      <el-table-column label="科目名称" align="left" prop="subjectName" />
      <el-table-column label="借贷方向" align="center" prop="directionType"  width="100">
        <template #default="scope">
          <FinSubjectDirectionType :direction-type-val="scope.row.directionType"></FinSubjectDirectionType>
        </template>
      </el-table-column>
      <el-table-column label="期初" align="center"  >
        <el-table-column label="借方" align="center" >
          <template #default="scope">
              <el-input-number     controls-position="right" size="small" v-model="scope.row.beginJieValue"  @change="handleUpdateData(scope.row)" />
          </template>
        </el-table-column>
        <el-table-column label="贷方" align="center"  >
          <template #default="scope">
              <el-input-number controls-position="right" size="small" v-model="scope.row.beginDaiValue"  @change="handleUpdateData(scope.row)" />
          </template>
        </el-table-column>
      </el-table-column>

      <el-table-column label="本期发生额" align="center"  >
        <el-table-column label="借方" align="center"  >
          <template #default="scope">
            <div>
              <el-input-number controls-position="right" size="small" v-model="scope.row.monthJieValue"  @change="handleUpdateData(scope.row)" />
            </div>
          </template>
        </el-table-column>
        <el-table-column label="贷方" align="center">
          <template #default="scope">
              <el-input-number controls-position="right" size="small" v-model="scope.row.monthDaiValue"  @change="handleUpdateData(scope.row)" />
          </template>
        </el-table-column>
      </el-table-column>

      <el-table-column label="本年累计发生额" align="center"  >
        <el-table-column label="借方" align="center"  >
          <template #default="scope">
            <div>
              <el-input-number controls-position="right" size="small" v-model="scope.row.yearJieValue"  @change="handleUpdateData(scope.row)" />
            </div>
          </template>
        </el-table-column>
        <el-table-column label="贷方" align="center"  >
          <template #default="scope">
            <div>
              <el-input-number controls-position="right" size="small" v-model="scope.row.yearDaiValue"  @change="handleUpdateData(scope.row)" />
            </div>
          </template>
        </el-table-column>
      </el-table-column>

      <el-table-column label="期末余额" align="center">
        <el-table-column label="借方" align="center">
          <template #default="scope">
              <el-input-number controls-position="right" size="small" v-model="scope.row.endJieValue"  @change="handleUpdateData(scope.row)" />
          </template>
        </el-table-column>
        <el-table-column label="贷方" align="center" >
          <template #default="scope">
              <el-input-number controls-position="right" size="small" v-model="scope.row.endDaiValue"  @change="handleUpdateData(scope.row)" />
          </template>
        </el-table-column>
      </el-table-column>

    </el-table>
    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改科目余额对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="FinSubjectMonthRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="上级科目id" prop="parentId">
          <el-input v-model="form.parentId" placeholder="请输入上级科目id" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="FinSubjectMonth">
import {
  listFinSubjectMonth,
  getFinSubjectMonth,
  delFinSubjectMonth,
  addFinSubjectMonth,
  updateFinSubjectMonth,
  importDefaultFinSubjectMonth
} from "@/api/project/FinSubjectMonth";
import FinSubjectDirectionType from "@/components/enumShow/FinSubjectDirectionType.vue";
const { proxy } = getCurrentInstance();

const FinSubjectMonthList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const sums = ref([]);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 1000,
    subjectType: '',
    hasGtZero:true,
    directionType: null,
    yearValue: null,
    monthValue: null,
    yearAndMonth: null,
    packageId: null,
  },
  rules: {
    subjectType: [
      { required: true, message: "类型不能为空", trigger: "change" }
    ],
    directionType: [
      { required: true, message: "借贷方向不能为空", trigger: "change" }
    ],
    subjectId: [
      { required: true, message: "科目id不能为空", trigger: "blur" }
    ],
    subjectCode: [
      { required: true, message: "科目代码不能为空", trigger: "blur" }
    ],
    subjectName: [
      { required: true, message: "科目不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询科目余额列表 */
function getList() {
  loading.value = true;
  listFinSubjectMonth(queryParams.value).then(response => {
    let valueMap = new Map();
    let listValue = new Array();
    response.rows.forEach(v=>{
      valueMap.set(v.subjectId,v)
    })
    //合计，“”，“”，期初借方（3），期初贷方（4），本期借方（5），本期贷方（6）,本年借方（7），本年贷方（8）,期末借方（9），期末贷方（10）,
    sums.value = [h('div', { style: { textDecoration: 'underline' } }, ['合计',]),"","",0,0,0,0,0,0,0,0]
    response.rows.forEach(v=>{
      if(v.subjectParentId && v.subjectParentId>0){
        let parentV = valueMap.get(v.subjectParentId)
        //parentV.hasChildren = true;
        if(parentV.children===undefined){
          parentV.children = [];
        }
        parentV.children.push(v)
        console.log("parentV->",parentV.subjectId,parentV.subjectName,v.subjectId,v.subjectName,parentV)
      }else{
        listValue.push(v);
        sums.value[3] = sums.value[3] + Number.parseFloat(v.beginJieValue);
        sums.value[4] = sums.value[4] + Number.parseFloat(v.beginDaiValue);
        sums.value[5] = sums.value[5] + Number.parseFloat(v.monthJieValue);
        sums.value[6] = sums.value[6] + Number.parseFloat(v.monthDaiValue);
        sums.value[7] = sums.value[7] + Number.parseFloat(v.yearJieValue);
        sums.value[8] = sums.value[8] + Number.parseFloat(v.yearDaiValue);
        sums.value[9] = sums.value[9] + Number.parseFloat(v.endJieValue);
        sums.value[10] = sums.value[10] + Number.parseFloat(v.endDaiValue);
      }
    })
    FinSubjectMonthList.value = listValue;
    console.log("FinSubjectMonthList->",FinSubjectMonthList.value)
    console.log("valueMap->",valueMap)
    total.value = response.rows.length;
    loading.value = false;
  });
}

function getSummaries  (param) {
  sums.value[3] = Number.parseFloat(sums.value[3],2).toFixed(2) ;
  sums.value[4] = Number.parseFloat(sums.value[4],2).toFixed(2) ;
  sums.value[5] = Number.parseFloat(sums.value[5],2).toFixed(2) ;
  sums.value[6] = Number.parseFloat(sums.value[6],2).toFixed(2) ;
  sums.value[7] = Number.parseFloat(sums.value[7] ,2).toFixed(2);
  sums.value[8] = Number.parseFloat(sums.value[8] ,2).toFixed(2);
  sums.value[9] = Number.parseFloat(sums.value[9] ,2).toFixed(2);
  sums.value[10] = Number.parseFloat(sums.value[10] ,2).toFixed(2);
  return sums.value
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    parentId: null,
    parentName: null,
    subjectType: null,
    directionType: null,
    subjectId: null,
    subjectCode: null,
    subjectName: null,
    beginJieValue: null,
    beginDaiValue: null,
    endJieValue: null,
    endDaiValue: null,
    beginYearValue: null,
    monthSumValue: null,
    yearSumValue: null,
    yearValue: null,
    monthValue: null,
    yearAndMonth: null,
    packageId: null,
    createId: null,
    createBy: null,
    createTime: null,
    updateId: null,
    updateBy: null,
    updateTime: null,
    remark: null
  };
  proxy.resetForm("FinSubjectMonthRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

function handleImportDefaultFinSubjectMonth(){
  importDefaultFinSubjectMonth().then(response => {
    proxy.$modal.msgSuccess("初始化成功");
    getList();
  });
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加科目余额";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getFinSubjectMonth(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改科目余额";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["FinSubjectMonthRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateFinSubjectMonth(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addFinSubjectMonth(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

function handleUpdateData(row){
  updateFinSubjectMonth(row).then(response => {
    proxy.$modal.msgSuccess("更新成功");
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除科目余额编号为"' + _ids + '"的数据项？').then(function() {
    return delFinSubjectMonth(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('project/FinSubjectMonth/export', {
    ...queryParams.value
  }, `FinSubjectMonth_${new Date().getTime()}.xlsx`)
}

getList();
</script>
